package com.tengju.support.application.shared;


import lombok.extern.slf4j.Slf4j;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.block.BlockBorder;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.*;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.chart.renderer.category.StandardBarPainter;
import org.jfree.chart.renderer.xy.StandardXYBarPainter;
import org.jfree.chart.ui.RectangleInsets;
import org.jfree.chart.ui.TextAnchor;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;

import java.awt.*;
import java.io.File;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.Map.Entry;


@Slf4j
public class PictureUtils {

//    private static String PICTURE_PATH = "";

    private static String PICTURE_PATH = "tmp/pic/";


    private static String NO_DATA_MSG = "暂无数据";
    private static Font FONT = new Font("宋体", Font.PLAIN, 20);
    // 颜色
    public static Color[] CHART_COLORS = {
            new Color(31,129,188), new Color(92,92,97), new Color(144,237,125), new Color(255,188,117),
            new Color(153,158,255), new Color(255,117,153), new Color(253,236,109), new Color(128,133,232),
            new Color(158,90,102),new Color(255, 204, 102) };

    static{
        setChartTheme();
    }
    /**
     * 中文主题样式 解决乱码
     */
    public static void setChartTheme() {
        // 设置中文主题样式 解决乱码
        StandardChartTheme chartTheme = new StandardChartTheme("CN");
        // 设置标题字体
        chartTheme.setExtraLargeFont(FONT);
        // 设置图例的字体
        chartTheme.setRegularFont(FONT);
        // 设置轴向的字体
        chartTheme.setLargeFont(FONT);
        chartTheme.setSmallFont(FONT);
        chartTheme.setTitlePaint(new Color(51, 51, 51));
        chartTheme.setSubtitlePaint(new Color(85, 85, 85));

        // 设置标注
        chartTheme.setLegendBackgroundPaint(Color.WHITE);
        chartTheme.setLegendItemPaint(Color.BLACK);
        chartTheme.setChartBackgroundPaint(Color.WHITE);

        // 绘制颜色绘制颜色.轮廓供应商
        // paintSequence,outlinePaintSequence,strokeSequence,outlineStrokeSequence,shapeSequence
        Paint[] outlinePaintSequence = new Paint[] { Color.WHITE };
        // 绘制器颜色源
        DefaultDrawingSupplier drawingSupplier = new DefaultDrawingSupplier(CHART_COLORS, CHART_COLORS, outlinePaintSequence,
                DefaultDrawingSupplier.DEFAULT_STROKE_SEQUENCE, DefaultDrawingSupplier.DEFAULT_OUTLINE_STROKE_SEQUENCE,
                DefaultDrawingSupplier.DEFAULT_SHAPE_SEQUENCE);
        chartTheme.setDrawingSupplier(drawingSupplier);

        // 绘制区域
        chartTheme.setPlotBackgroundPaint(Color.WHITE);
        // 绘制区域外边框
        chartTheme.setPlotOutlinePaint(Color.WHITE);
        // 链接标签颜色
        chartTheme.setLabelLinkPaint(new Color(8, 55, 114));
        chartTheme.setLabelLinkStyle(PieLabelLinkStyle.CUBIC_CURVE);

        chartTheme.setAxisOffset(new RectangleInsets(5, 12, 5, 12));
        // X坐标轴垂直网格颜色
        chartTheme.setDomainGridlinePaint(new Color(192, 208, 224));
        // Y坐标轴水平网格颜色
        chartTheme.setRangeGridlinePaint(new Color(192, 192, 192));

        chartTheme.setBaselinePaint(Color.WHITE);
        // 不确定含义
        chartTheme.setCrosshairPaint(Color.BLUE);
        // 坐标轴标题文字颜色
        chartTheme.setAxisLabelPaint(new Color(51, 51, 51));
        // 刻度数字
        chartTheme.setTickLabelPaint(new Color(67, 67, 72));
        // 设置柱状图渲染
        chartTheme.setBarPainter(new StandardBarPainter());
        // XYBar 渲染
        chartTheme.setXYBarPainter(new StandardXYBarPainter());

        chartTheme.setItemLabelPaint(Color.black);
        // 温度计
        chartTheme.setThermometerPaint(Color.white);

        ChartFactory.setChartTheme(chartTheme);
    }

    public PictureUtils() {
    }


    /**
     * 必须设置文本抗锯齿
     */
    public static void setAntiAlias(JFreeChart chart) {
        chart.setTextAntiAlias(false);

    }

    /**
     * 设置图例无边框，默认黑色边框
     */
    public static void setLegendEmptyBorder(JFreeChart chart) {
        chart.getLegend().setFrame(new BlockBorder(Color.WHITE));

    }

    /**
     * 提供静态方法：获取报表图形1：饼状图
     * @param title    标题
     * @param data    数据
     * @param picName    图片名
     */
    public static void createPiePort(String title, Map<String,Double> data, String picName){
        try {
            // 如果不使用Font,中文将显示不出来
            DefaultPieDataset pds = new DefaultPieDataset();

            // 获取迭代器：
            Set<Map.Entry<String, Double>> set =  data.entrySet();
            Iterator iterator= set.iterator();
            Entry entry;
            while(iterator.hasNext()){
                entry=(Entry) iterator.next();
                pds.setValue(entry.getKey().toString(),Double.parseDouble(entry.getValue().toString()));
            }

            // 生成一个饼图的图表
            // 分别是:显示图表的标题、需要提供对应图表的DateSet对象、是否显示图例、是否生成贴士以及是否生成URL链接
            JFreeChart chart = ChartFactory.createPieChart(title, pds, true, true, true);
            setPieRender((PiePlot) chart.getPlot());

            //将内存中的图片写到本地硬盘
            org.jfree.chart.ChartUtils.saveChartAsPNG(new File(PICTURE_PATH + picName), chart,800,500);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 提供静态方法：获取报表图形1：饼状图
     * @param title    标题
     * @param data    数据
     * @param picName    图片名
     */
    public static void createBarPort(String title, Map<String,Double> data, String picName){
        try {
            // 如果不使用Font,中文将显示不出来
            DefaultCategoryDataset  pds = new DefaultCategoryDataset();

            // 获取迭代器：
            Set<Map.Entry<String, Double>> set =  data.entrySet();
            Iterator iterator= set.iterator();
            Entry entry;
            while(iterator.hasNext()){
                entry=(Entry) iterator.next();
                pds.setValue(Double.parseDouble(entry.getValue().toString()),entry.getKey().toString(),entry.getKey().toString());
            }

            // 生成一个饼图的图表
            // 分别是:显示图表的标题、需要提供对应图表的DateSet对象、是否显示图例、是否生成贴士以及是否生成URL链接
            JFreeChart chart = ChartFactory.createBarChart(title,"分类","数量",
                    pds, PlotOrientation.VERTICAL, true, true, false);
            CategoryPlot plot = (CategoryPlot)chart.getPlot();

            plot.setNoDataMessage(NO_DATA_MSG);
            plot.setInsets(new RectangleInsets(10, 10, 5, 10));

            BarRenderer renderer = (BarRenderer) plot.getRenderer();
            renderer.setDefaultItemLabelsVisible(true);
            renderer.setDefaultItemLabelGenerator(
                    new StandardCategoryItemLabelGenerator(StandardCategoryItemLabelGenerator.DEFAULT_LABEL_FORMAT_STRING,
                    NumberFormat.getInstance()));
            // 位置
            renderer.setDefaultPositiveItemLabelPosition(
                    new ItemLabelPosition(ItemLabelAnchor.OUTSIDE1, TextAnchor.BOTTOM_CENTER));
            renderer.setMaximumBarWidth(0.1);
            renderer.setMinimumBarLength(0.1);

            //将内存中的图片写到本地硬盘
            org.jfree.chart.ChartUtils.saveChartAsPNG(new File(PICTURE_PATH + picName), chart,800,600);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




    /**
     * 获取报表图形3：折线图
     * @param title        标题
     * @param data        数据
     * @param xName        分类（第一季，第二季.....）
     * @param yName    柱状图的数量单位
     * @param picName        图片名
     */
    public static String createLinePort(String title, TreeMap<String, BigDecimal> data, String xName, String yName, String picName){
        try {

            //种类数据集
            DefaultCategoryDataset dataset = new DefaultCategoryDataset();
            //获取迭代器：
            Set<Entry<String, BigDecimal>> set =  data.entrySet();
            Iterator iterator= set.iterator();
            Entry entry;
            while(iterator.hasNext()){
                entry=(Entry) iterator.next();

                dataset.setValue(Double.parseDouble(
                        //y
                        entry.getValue().toString()),
                        //名称
                        title,
                        //x
                        entry.getKey().toString());
            }
            //创建折线图,折线图分水平显示和垂直显示两种
            JFreeChart chart = ChartFactory.createLineChart(
                    //2D折线图
                    title, xName, yName, dataset,
                    PlotOrientation.VERTICAL,
                    // 是否显示图例(对于简单的柱状图必须是false)
                    false,
                    // 是否生成工具
                    false,
                    // 是否生成URL链接
                    false);
            //得到绘图区
            setLineRender((CategoryPlot)chart.getPlot(),true,true);

            int size = data.size();
            Integer width = 1000;
            if (size > 5) {
                width = 200 * size;
            }
            File file = new File(PICTURE_PATH + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")));
            if (!file.exists()) {
                file.mkdirs();
            }
            String path = PICTURE_PATH + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")) + "/" + picName;
            org.jfree.chart.ChartUtils.saveChartAsPNG(new File(path), chart, width,600);

            return path;
        } catch (Exception e) {
            log.error("生产折线图失败",e);
            return "";
        }
    }

    /**
     * 设置折线图样式
     *
     * @param plot
     * @param isShowDataLabels
     *            是否显示数据标签
     */
    public static void setLineRender(CategoryPlot plot, boolean isShowDataLabels, boolean isShapesVisible) {
        plot.setNoDataMessage(NO_DATA_MSG);
        plot.setInsets(new RectangleInsets(10, 10, 0, 10), false);
        LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
        renderer.setDefaultStroke(new BasicStroke(1.5F));
        if (isShowDataLabels) {
            renderer.setDefaultItemLabelsVisible(true);
            renderer.setDefaultItemLabelGenerator(new StandardCategoryItemLabelGenerator(StandardCategoryItemLabelGenerator.DEFAULT_LABEL_FORMAT_STRING,
                    NumberFormat.getInstance()));
            // 位置
            renderer.setDefaultPositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE1, TextAnchor.BOTTOM_CENTER));
        }
        // 数据点绘制形状
        renderer.setDefaultShapesVisible(isShapesVisible);
        setXAixs(plot);
        setYAixs(plot);

    }

    /**
     * 设置饼状图渲染
     */
    public static void setPieRender(PiePlot plot) {

        plot.setNoDataMessage(NO_DATA_MSG);
        plot.setInsets(new RectangleInsets(10, 10, 5, 10));
        plot.setInsets(new RectangleInsets(0, 0, 0, 0));
        // 圆形
        plot.setCircular(true);

        plot.setLabelGap(0.01);
        plot.setInteriorGap(0.05D);
        // 图例形状
        plot.setLegendItemShape(new Rectangle(10, 10));
        plot.setIgnoreNullValues(true);
        // 去掉背景色
        plot.setLabelBackgroundPaint(null);
        // 去掉阴影
        plot.setLabelShadowPaint(null);
        // 去掉边框
        plot.setLabelOutlinePaint(null);
        plot.setShadowPaint(null);
        // 显示标签数据
        // 0:category 1:value:2 :percentage
        plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}:{2}"));
    }

    /**
     * 设置类别图表(CategoryPlot) X坐标轴线条颜色和样式
     *
     * @param plot
     */
    public static void setXAixs(CategoryPlot plot) {
        Color lineColor = new Color(31, 121, 170);
        plot.getDomainAxis().setCategoryLabelPositions(CategoryLabelPositions.UP_45);
        // X坐标轴颜色
        plot.getDomainAxis().setAxisLinePaint(lineColor);
        // X坐标轴标记|竖线颜色
        plot.getDomainAxis().setTickMarkPaint(lineColor);

    }

    /**
     * 设置类别图表(CategoryPlot) Y坐标轴线条颜色和样式 同时防止数据无法显示
     *
     * @param plot
     */
    public static void setYAixs(CategoryPlot plot) {
        Color lineColor = new Color(31, 121, 170);
        NumberAxis axis = (NumberAxis)plot.getRangeAxis();
        // Y坐标轴颜色
        axis.setAxisLinePaint(lineColor);
        // Y坐标轴标记|竖线颜色
        axis.setTickMarkPaint(lineColor);
        // false隐藏Y刻度
        axis.setAxisLineVisible(true);
        axis.setTickMarksVisible(true);
        axis.setAutoRange(true);
        axis.setAutoTickUnitSelection(true);
        axis.setAutoRangeIncludesZero(false);
        // Y轴网格线条
        plot.setRangeGridlinePaint(new Color(192, 192, 192));
        plot.setRangeGridlineStroke(new BasicStroke(1));

        // 设置顶部Y坐标轴间距,防止数据无法显示
        plot.getRangeAxis().setUpperMargin(0.1);
        // 设置底部Y坐标轴间距
        plot.getRangeAxis().setLowerMargin(0.1);

    }

    /**
     * 设置XY图表(XYPlot) X坐标轴线条颜色和样式
     *
     * @param plot
     */
    public static void setXY_XAixs(XYPlot plot) {
        Color lineColor = new Color(31, 121, 170);
        // X坐标轴颜色
        plot.getDomainAxis().setAxisLinePaint(lineColor);
        // X坐标轴标记|竖线颜色
        plot.getDomainAxis().setTickMarkPaint(lineColor);

    }

    /**
     * 设置XY图表(XYPlot) Y坐标轴线条颜色和样式 同时防止数据无法显示
     *
     * @param plot
     */
    public static void setXY_YAixs(XYPlot plot) {
        Color lineColor = new Color(192, 208, 224);
        ValueAxis axis = plot.getRangeAxis();
        // X坐标轴颜色
        axis.setAxisLinePaint(lineColor);
        // X坐标轴标记|竖线颜色
        axis.setTickMarkPaint(lineColor);
        // 隐藏Y刻度
        axis.setAxisLineVisible(false);
        axis.setTickMarksVisible(false);
        // Y轴网格线条
        plot.setRangeGridlinePaint(new Color(192, 192, 192));
        plot.setRangeGridlineStroke(new BasicStroke(1));
        plot.setDomainGridlinesVisible(false);

        // 设置顶部Y坐标轴间距,防止数据无法显示
        plot.getRangeAxis().setUpperMargin(0.12);
        // 设置底部Y坐标轴间距
        plot.getRangeAxis().setLowerMargin(0.12);

    }




    public static void clearFile(LocalDate localDate) {
        log.info("开始清理图片文件，path:{}", PICTURE_PATH);
        try {
            File file = new File(PICTURE_PATH + localDate.format(DateTimeFormatter.ofPattern("yyyyMMdd")));
            PictureUtils.delFile(file);
            file.delete();
        } catch (Exception var3) {
            log.error("清理清理图片失败 fullName:{} time:{}", PICTURE_PATH, LocalDateTime.now().minusDays(1L));
        }
    }

    private static void delFile(File file) {
        if (file != null && file.exists()) {
            if (file.isDirectory()) {
                File[] subFileList = file.listFiles();
                if (subFileList != null && subFileList.length > 0) {
                    File[] var3 = subFileList;
                    int var4 = subFileList.length;

                    for(int var5 = 0; var5 < var4; ++var5) {
                        File subFile = var3[var5];
                        if (subFile.isDirectory() && Objects.requireNonNull(subFile.listFiles()).length > 0) {
                            PictureUtils.delFile(subFile);
                        }

                        subFile.delete();
                    }
                }
            } else {
                file.delete();
            }
        }

    }

    public static void main(String[] args) {
        TreeMap<String, BigDecimal> map1= new TreeMap<>();
        //设置第一期的投票信息
        map1.put("200201", BigDecimal.valueOf(300000));
        map1.put("200202", BigDecimal.valueOf(300000));
        map1.put("200203", BigDecimal.valueOf(300000));
        map1.put("200204", BigDecimal.valueOf(300000));
        map1.put("200205", BigDecimal.valueOf(300000));
        map1.put("200206", BigDecimal.valueOf(300000));
        map1.put("200207", BigDecimal.valueOf(300000));
        map1.put("200208", BigDecimal.valueOf(300000));
        map1.put("200209", BigDecimal.valueOf(300000));
        map1.put("200210", BigDecimal.valueOf(300000));
        map1.put("200211", BigDecimal.valueOf(300000));
        map1.put("200212", BigDecimal.valueOf(250000));
        map1.put("200213", BigDecimal.valueOf(300000));
        map1.put("200214", BigDecimal.valueOf(300000));
        map1.put("200215", BigDecimal.valueOf(300000));

        System.out.println(createLinePort("近7日金额(日报)",map1,"日期","金额（元）","a2"));


//        Map<String, Double> map=new HashMap<String, Double>();
//        map.put("冠心病1", (double) 1000);
//        map.put("脑卒中2", (double) 700);
//        map.put("肺结核3", (double) 600);
//        map.put("糖尿病4", (double) 400);
//        map.put("高血压5", (double) 100);
//        map.put("精神病6", (double) 2000);
//        map.put("冠心病7", (double) 1000);
//        map.put("脑卒中8", (double) 700);
//        map.put("肺结核9", (double) 600);
//        map.put("糖尿病0", (double) 400);
//        map.put("高血压11", (double) 100);
//        map.put("精神病12", (double) 2000);
//        map.put("冠心病13", (double) 1000);
//        map.put("脑卒中14", (double) 700);
//        map.put("肺结核15", (double) 600);
//        map.put("糖尿病16", (double) 400);
//        map.put("高血压17", (double) 100);
//        map.put("精神病18", (double) 2000);
//        map.put("冠心病19", (double) 1000);
//        map.put("脑卒中20", (double) 700);
//        map.put("肺结核21", (double) 600);
//        map.put("糖尿病22", (double) 400);
//        map.put("高血压23", (double) 100);
//        map.put("精神病24", (double) 2000);
//        createPiePort("慢病统计结果", map,"a1");


//        map1.put("2020-02-03-8", (double) 700);
//        map1.put("2020-02-04-9", (double) 1000);
//        map1.put("2020-02-05-10", (double) 600);
//        map1.put("2020-02-06-11", (double) 400);
//        map1.put("2020-02-07-12", (double) 4000);
//        map1.put("2020-02-08-13", (double) 1200);
//        map1.put("2020-02-09-14", (double) 800);
//        map1.put("2020-02-03-15", (double) 700);
//        map1.put("2020-02-04-16", (double) 1000);
//        map1.put("2020-02-05-17", (double) 600);
//        map1.put("2020-02-06-18", (double) 400);
//        map1.put("2020-02-07-19", (double) 4000);
//        map1.put("2020-02-08-20", (double) 1200);
//        map1.put("2020-02-09-21", (double) 800);
//        map1.put("2020-02-03-22", (double) 700);
//        map1.put("2020-02-04-23", (double) 1000);
//        map1.put("2020-02-05-24", (double) 600);
//        map1.put("2020-02-06-25", (double) 400);
//        map1.put("2020-02-07-26", (double) 4000);
//        map1.put("2020-02-08-27", (double) 1200);
//        map1.put("2020-02-09-28", (double) 800);


//        Map<String, Double> map2=new HashMap<String, Double>();
//        map2.put("冠心病", (double) 1000);
//        map2.put("脑卒中2", (double) 700);
//        map2.put("肺结核3", (double) 600);
//        map2.put("糖尿病4", (double) 400);
//        map2.put("高血压5", (double) 100);
//        map2.put("精神病6", (double) 2000);
//        map2.put("冠心病7", (double) 1000);
//        map2.put("脑卒中8", (double) 700);
//        map2.put("肺结核9", (double) 600);
//        map2.put("糖尿病0", (double) 400);
//        map2.put("高血压11", (double) 100);
//        map2.put("精神病12", (double) 2000);
//        map2.put("冠心病13", (double) 1000);
//        map2.put("脑卒中14", (double) 700);
//        map2.put("肺结核15", (double) 600);
//        map2.put("糖尿病16", (double) 400);
//        map2.put("高血压17", (double) 100);
//        map2.put("精神病18", (double) 2000);
//        map2.put("冠心病19", (double) 1000);
//        map2.put("脑卒中20", (double) 700);
//        map2.put("肺结核21", (double) 600);
//        map2.put("糖尿病22", (double) 400);
//        map2.put("高血压23", (double) 100);
//        map2.put("精神病24", (double) 2000);
//        createBarPort("慢病统计结果", map2,"a3");
    }

}